package com.java.frontweb.controller;

import com.java.frontweb.intercepters.UserLoginHandlerInterceptor;
import com.java.frontweb.pojo.Order;
import com.java.frontweb.pojo.User;
import com.java.frontweb.service.CartService;
import com.java.frontweb.service.ItemService;
import com.java.frontweb.service.OrderService;
import com.java.frontweb.service.UserService;
import com.java.frontweb.thred.UserThreadLocal;
import com.java.manage.pojo.TbItem;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName OrderController
 * @Description 前台订单处理
 * @Author Trigger Wu
 * @Date 2018/9/2219:22
 * @Version 1.0
 **/
@RequestMapping("/rest/order")
@Controller
public class OrderController {


    @Autowired
    private ItemService itemService;

    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private CartService cartService;

    /*
     *  订单确认页
     *
     * @author Tigger Wu
     * @date 2018/9/22 19:42
     * @param [itemId]
     * @return org.springframework.web.servlet.ModelAndView
     */
    @RequestMapping(value = "{itemId}", method = RequestMethod.GET)
    public ModelAndView toOrder(@PathVariable("itemId") Long itemId) {
        ModelAndView mv = new ModelAndView("order");
        TbItem item = itemService.queryById(itemId);
        mv.addObject("item", item);
        return mv;
    }

    /*
     * 提交订单确认
     *
     * @author Tigger Wu
     * @date 2018/9/23 0:58
     * @param []
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @ResponseBody
    @RequestMapping(value = "submit",method = RequestMethod.POST)
    public Map<String,Object> submit(Order order) throws IOException {
        HashMap<String, Object> map = new HashMap<>();

        String orderId = orderService.submit(order);
        if(StringUtils.isEmpty(orderId)){
            //没有成功,提交失败
            map.put("status",500);
        }else{
            //返回提交成功
            map.put("status",200);
            map.put("data",orderId);
        }
        return map;
    }

    /*
     *  返回成功页
     * 
     * @author Tigger Wu
     * @date 2018/9/25  | 10:35
     * @param [OrderId]
     * @return org.springframework.web.servlet.ModelAndView
     */
    @RequestMapping(value = "success",method = RequestMethod.GET)
    public ModelAndView success(@RequestParam ("id")String OrderId){
        ModelAndView mv  = new ModelAndView("success");
        //获取订单信息
        Order order = orderService.queryByOrderId(OrderId);
        mv.addObject("order",order);
        mv.addObject("date",new DateTime().plusDays(2).toString("MM月dd日"));
        return mv;
    }
}
